package com.czf.CurriculumVitae.control;

import com.czf.CurriculumVitae.bean.Admin;
import com.czf.CurriculumVitae.bean.Result;
import com.czf.CurriculumVitae.service.DBService;
import com.mysql.cj.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;
import java.util.UUID;

/**
 * @author chen
 * @Description: 用户注册
 * @date 2021/3/25 11:11
 */
@WebServlet("/v1/register/insert")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.    处理乱码,把编码字典设置为utf-8
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/json;charset=utf-8");

        //2.    接收前端发送过来的数据内容
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String id = UUID.randomUUID().toString().replace("-","").toLowerCase();
        System.out.println("---------------------->>> userid: " + id);

        Admin admin = new Admin(id,username,password);
        int row = DBService.userRegister(admin);

        Result result = null;
        if (row > 0) {
//            result = new Result(0,"账号注册成功");
            Admin admin1 = DBService.userLogin(admin);
            if (admin1 != null && !StringUtils.isNullOrEmpty(admin1.getUsername()) && !StringUtils.isNullOrEmpty(admin1.getPassword())){
                result = new Result(0,"注册成功",admin1);
            }else {
                result = new Result(-1,"账号注册失败");
            }
        }else {
            result = new Result(-1,"账号注册失败");
        }
        response.getWriter().append(result.toJSON());
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }
}
